package com.lxw.rmg.menu.controller;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxw.common.utils.PageUtils;
import com.lxw.common.utils.R;
//import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.lxw.rmg.menu.entity.MatterEntity;
import com.lxw.rmg.menu.entity.NutrientTableEntity;
import com.lxw.rmg.menu.service.MatterService;
import com.lxw.rmg.menu.service.NutrientTableService;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lxw.rmg.menu.entity.MenuEntity;
import com.lxw.rmg.menu.service.MenuService;

import javax.servlet.http.HttpServletRequest;


/**
 * 菜单表
 *
 * @author lxw
 * @email 
 * @date 2023-03-21 19:59:48
 */
@RestController
@RequestMapping("menu/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;
    @Autowired
    private MatterService matterService;
    @Autowired
    private NutrientTableService nutrientTableService;


    //通过cookie查看是否什么角色
//    public String getRoleByCooike(String cookie){
//        new QueryWrapper<>().select("")
//        return "ok";
//    }


    //获取菜名
    @RequestMapping("/dishName")
//    @RequiresPermissions("menu:menu:list")
    public R getDishName(){
        ArrayList<String> dn = new ArrayList<>();
        List<MenuEntity> list = menuService.list();
        for (MenuEntity menuEntity : list) {
            dn.add(menuEntity.getDishName());
        }

        return R.ok().put("dn", dn);
    }
    /**
     * 列表
     */
    @RequestMapping("/list")
//    @RequiresPermissions("menu:menu:list")
    public R list(@RequestParam Map<String, Object> params, HttpServletRequest request){


        PageUtils page = menuService.queryPage(params);

        //获取参数
        String dishName = (String)params.get("dishName");
        System.out.println("dishName ==>  " + dishName);
        if (!StringUtils.isNullOrEmpty(dishName) && !" ".equals(dishName)){
            List menuEntityList = menuService.list(
                    new QueryWrapper<MenuEntity>().eq("dish_name", dishName));
            page.setList(menuEntityList);
            page.setTotalCount(menuEntityList.size());
        }


        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
//    @RequiresPermissions("menu:menu:info")
    public R info(@PathVariable("id") String id){
		MenuEntity menu = menuService.getById(id);


        return R.ok().put("menu", menu);
    }


    /**
     * 信息
     */
//    @RequestMapping("/info/{dishName}")
////    @RequiresPermissions("menu:menu:info")
//    public R info(@PathVariable("dishName") String dishName){
//        MenuEntity menu = menuService.getOne(new QueryWrapper<MenuEntity>().eq("dish_name",dishName));
//
//
//        return R.ok().put("menu", menu);
//    }
//    @RequestMapping("/info/{id}")
////    @RequiresPermissions("menu:menu:info")
//    public R info2(@PathVariable("id") String id){
//        MenuEntity menu = menuService.getOne(new QueryWrapper<MenuEntity>().eq("id",id));
//
//
//        return R.ok().put("menu", menu);
//    }
    /**
     * 保存
     */
    @RequestMapping("/save")
//    @RequiresPermissions("menu:menu:save")
    @Transactional //添加事务设计多表操作
    public R save(@RequestBody MenuEntity menu){
        menu.setDishCode(UUID.randomUUID().toString());
//        //保存时获取对比物料
//        String reqMate = menu.getReqMate();
//        if (reqMate.contains(",") || reqMate.contains("_")) {
//            String[] rms = reqMate.split(",");
//            for (String rm : rms) {
//                //获取每一种物料
//                String[] s = rm.split("_");
//                //获取物料表
//                MatterEntity matterEntity = matterService.getOne(new QueryWrapper<MatterEntity>().eq("mate_name", s[0]).ge("current_inventory", Integer.parseInt(s[1])));
//
//                if (null == matterEntity) {
//                    return R.error(s[0] + "物料不足");
//                }
////                //如果库存有物料就减少物料 （应该下单时减少）
////
////                matterEntity.setCurrentInventory(matterEntity.getCurrentInventory()-Integer.parseInt(s[1]));
////                matterService.updateById(matterEntity);
//            }
//        }
        NutrientTableEntity nutrientTable = new NutrientTableEntity();
        ;
        nutrientTable.setSugar(Float.parseFloat((String) menu.getFormData().get("sugar")));
        nutrientTable.setFat(Float.parseFloat((String) menu.getFormData().get("fat")));
        nutrientTable.setEnergy(Float.parseFloat((String) menu.getFormData().get("energy")));
        nutrientTable.setProtein(Float.parseFloat((String) menu.getFormData().get("protein")));
        nutrientTable.setCarbohydrate(Float.parseFloat((String) menu.getFormData().get("carbohydrate")));
        nutrientTable.setSaturatedFat(Float.parseFloat((String) menu.getFormData().get("saturatedFat")));
        nutrientTable.setTransFat(Float.parseFloat((String) menu.getFormData().get("transFat")));
        nutrientTable.setCholesterol(Float.parseFloat((String) menu.getFormData().get("cholesterol")));
        nutrientTable.setSodium(Float.parseFloat((String) menu.getFormData().get("sodium")));

        nutrientTable.setDishName((String) menu.getDishName());

        nutrientTableService.save(nutrientTable);
         menuService.save(menu);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("menu:menu:update")
    @Transactional
    public R update(@RequestBody MenuEntity menu){
        NutrientTableEntity nutrientTable = nutrientTableService.getOne(new QueryWrapper<NutrientTableEntity>().eq("dish_code", menu.getDishCode()));
        nutrientTable.setSugar(Float.parseFloat((String) menu.getFormData().get("sugar")));
        nutrientTable.setFat(Float.parseFloat((String) menu.getFormData().get("fat")));
        nutrientTable.setEnergy(Float.parseFloat((String) menu.getFormData().get("energy")));
        nutrientTable.setProtein(Float.parseFloat((String) menu.getFormData().get("protein")));
        nutrientTable.setCarbohydrate(Float.parseFloat((String) menu.getFormData().get("carbohydrate")));
        nutrientTable.setSaturatedFat(Float.parseFloat((String) menu.getFormData().get("saturatedFat")));
        nutrientTable.setTransFat(Float.parseFloat((String) menu.getFormData().get("transFat")));
        nutrientTable.setCholesterol(Float.parseFloat((String) menu.getFormData().get("cholesterol")));
        nutrientTable.setSodium(Float.parseFloat((String) menu.getFormData().get("sodium")));
        //先通过菜品编码查询出营养成分表id


        nutrientTableService.updateById(nutrientTable);
		menuService.updateById(menu);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
//    @RequiresPermissions("menu:menu:delete")
    @Transactional
    public R delete(@RequestBody Integer[] ids){
        Collection<MenuEntity> menuEntities = menuService.listByIds(Arrays.asList(ids));
        //删除营养分析
        for (MenuEntity m : menuEntities) {
            nutrientTableService.remove(new QueryWrapper<NutrientTableEntity>().eq("dish_name", m.getDishName()));

        }
		menuService.removeByIds(Arrays.asList(ids));
		//通过id查出菜品编码

        return R.ok();
    }

}
